﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;
using System.IO;
using cnFederal.FaCode;

namespace cnFederal
{

    public partial class EditSelectedAd : System.Web.UI.Page
    {

        CnfiAd _ad;
        CultureInfo _ci;
        string _imageUrl;
        public EditSelectedAd() 
        {
            _ci = new CultureInfo("nb-NO");
            CnfiAds.Load(true);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            int id = -1;
            CnfImages.Load();
            string query = Request.QueryString["Id"];
            if (string.IsNullOrWhiteSpace(query))
                txtRegDate.Text = DateTime.Now.Year + "-" + DateTime.Now.Month + "-" + DateTime.Now.Day;
            
            if (!string.IsNullOrWhiteSpace(query))
            {

                try
                {
                    id = int.Parse(query);
                }
                catch (Exception ex) { }
                if (id != -1)
                    Load(id);

            }
            if (Session["ImageUrl"] != null)
                this._imageUrl = Session["ImageUrl"].ToString();
            MainTable.Visible = UserIdentity.Autenticated;
        }

        public string ImageUrl
        {
            get { return _imageUrl; }
            set { _imageUrl = value; }
        }

        public void Load(int id)
        {
          
            _ad = CnfiAds.GetFaPostById(id);
            if (!IsPostBack && _ad != null)
            {
                txtRegDate.Text = _ad.DateRegistered.Year + "-" + _ad.DateRegistered.Month + "-" + _ad.DateRegistered.Day;
                txtTitle.Text = _ad.Title;
                txtDateStartPublish.Text = _ad.DateStartPublish.Year + "-" + _ad.DateStartPublish.Month + "-" + _ad.DateStartPublish.Day;
                txtEndPublish.Text = _ad.DateEndPublish.Year + "-" + _ad.DateEndPublish.Month + "-" + _ad.DateEndPublish.Day;
                
                txtDescription.Text = _ad.Description;
                TxtAdsUrl.Text = _ad.AdsUrl;
                if (_ad.Display == true)
                    RadioButtonEnable.Checked = true;
                else
                    RadioButtonDisable.Checked = true;
                imageSelected.ImageUrl = _ad.ImageUrl;
            }
        }
        protected void txtRegDate_TextChanged(object sender, EventArgs e)
        {



        }

        private void CheckHttp()
        {
         if(!this.TxtAdsUrl.Text.Contains(@"http://"))
         {
             string uri = @"http://" +this.TxtAdsUrl.Text;
             this.TxtAdsUrl.Text = uri;

         }
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            CheckHttp();
            int itemId = 0;
            if (_ad == null)
               itemId = CreateNew();
            else
                Update();

            string id = Request.QueryString["Id"];
            if (!string.IsNullOrWhiteSpace(id))
            {
                if(itemId == 0)
                itemId = Convert.ToInt32(id);
                if (_image != null)
                {
                    _image.LinkId = itemId;
                    _image.LinkType = (int)SysObjects.AD;
                    CnfImages.Save(_image);
                }
            }
            //string query = @"~/Admin/EditSelectedAd.aspx";
            Response.Redirect(AbsoluteURI);
        }

        private void Update()
        {
            _ad.DateEndPublish = DateTime.Parse(txtEndPublish.Text, _ci);
            _ad.DateStartPublish = DateTime.Parse(txtDateStartPublish.Text, _ci);
            _ad.Description = txtDescription.Text;
            _ad.AdsUrl = TxtAdsUrl.Text;
            if (!string.IsNullOrWhiteSpace(this.ImageUrl))
                _ad.ImageUrl = this.ImageUrl;
            _ad.Title = txtTitle.Text;
            if (RadioButtonEnable.Checked)
                _ad.Display = true;
            else
                _ad.Display = false;
            CnfiAds.Save(_ad);
        }

        private int CreateNew()
        {
            _ad = new CnfiAd();
            _ad.DateEndPublish = DateTime.Parse(txtEndPublish.Text, _ci);
            _ad.DateRegistered = DateTime.Now;
            _ad.DateStartPublish = DateTime.Parse(txtDateStartPublish.Text, _ci);
            _ad.Description = txtDescription.Text;
            _ad.AdsUrl = TxtAdsUrl.Text;
            _ad.ImageUrl = this.ImageUrl;
            _ad.Title = txtTitle.Text;
            if (RadioButtonEnable.Checked)
                _ad.Display = true;
            else
                _ad.Display = false;
           return CnfiAds.CreateNew(_ad);
        }

        protected void btnBrows_Click(object sender, EventArgs e)
        {
            UploadImage();
            //Response.Redirect(Request.RawUrl);

        }

        public string RootDomain
        {
            get
            {
                return HttpContext.Current.Request.Url.Authority;
            }
        }
        public string AbsoluteURI
        {
            get
            {
                return HttpContext.Current.Request.Url.AbsoluteUri;
            }
        }
        CnfImage _image;
        private void UploadImage()
        {
            string msg = "";
            if (fileupload1.HasFile)
            {
                try
                {
                    string[] sTypes = { "image/jpg", "image/jpeg", "image/pjpeg", "image/gif", "image/x-png", "image/png" };
                    bool bIsMatch = false;
                    foreach (string sType in sTypes)
                    {
                        if (String.Compare(sType, fileupload1.PostedFile.ContentType, true) == 0)
                            bIsMatch = true;
                    }

                    if (bIsMatch)
                    {
                        if (fileupload1.PostedFile.ContentLength < 1002400)
                        {
                            // string appPath = Request.PhysicalApplicationPath;

                            string filename = Path.GetFileName(fileupload1.PostedFile.FileName);
                            //fileupload1.SaveAs(Server.MapPath(Path.Combine("~/Images/", filename)));
                            _image = CnfImages.GetImageByName(fileupload1.FileName);
                            if (_image == null)
                            {
                                CnfImage img = new CnfImage();
                                img.Image = fileupload1.FileBytes;
                                img.ImageName = fileupload1.FileName;
                                if (_ad != null)
                                    img.LinkId = _ad.Id;
                                img.LinkType = (int)SysObjects.AD;
                                CnfImages.CreateNew(img);
                                _image = CnfImages.GetLastAddedImage();

                            }
                            this._imageUrl = "http://"+RootDomain + "/ImgHandler.ashx?id=" + _image.Id;
                            Session["ImageUrl"] = this._imageUrl;
                            this.imageSelected.ImageUrl = this._imageUrl;

                        }
                        else
                            msg = "Upload status: The file has to be less than 1 MB!";
                    }
                    else
                        msg = "Upload status: Only JPEG files are accepted!";
                }
                catch (Exception ex)
                {
                    msg = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
                }
            }

        }
        //private void UploadImage()
        //{
        //    string msg = "";
        //    if (fileupload1.HasFile)
        //    {
        //        try
        //        {
        //            if (fileupload1.PostedFile.ContentType == "image/jpeg")
        //            {
        //                if (fileupload1.PostedFile.ContentLength < 1002400)
        //                {
        //                    string filename = Path.GetFileName(fileupload1.FileName);
        //                    fileupload1.SaveAs(Server.MapPath("~/Images/") + filename);
        //                    this._imageUrl = "~/Images/" + filename;
        //                    Session["ImageUrl"] = this._imageUrl;
        //                    this.imageSelected.ImageUrl = this._imageUrl;

        //                }
        //                else
        //                    msg = "Upload status: The file has to be less than 1 MB!";
        //            }
        //            else
        //                msg = "Upload status: Only JPEG files are accepted!";
        //        }
        //        catch (Exception ex)
        //        {
        //            msg = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message;
        //        }
        //    }
        //}


        private bool _display;
        protected void RadioButtonEnable_CheckedChanged(object sender, EventArgs e)
        {
            Session["display"] = true;
        }

        protected void RadioButtonDisable_CheckedChanged(object sender, EventArgs e)
        {
            Session["display"] = false;
        }



    }
}